package com.weaver.qfengx;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 图像相关工具类
 * Created by YeShengtao on 2020/10/12 17:53
 */
public class ImageUtils {

    public static void headImage(OutputStream outputStream, String text, String textRgb,
                                 String bgRgb, int width, int height) throws IOException {
        int fontSize = (int) (Integer.min(width, height) / 3);
        Font font = new Font("微软雅黑", Font.PLAIN, fontSize);
        headImage(outputStream, text, font, textRgb, bgRgb, width, height);
    }

    /**
     * 生成文字头像
     *
     * @param text    头像文字
     * @param textRgb 文字颜色RGB值
     * @param bgRgb   背景颜色RGB值
     */
    public static void headImage(OutputStream outputStream, String text, Font font, String textRgb,
                                 String bgRgb, int width, int height) throws IOException {

//        // 截取文本前两个字符（一个中文，或者两个字母）
//        text = StringUtils.subStringByChar(text, 2);

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.setColor(Color.decode(textRgb));
        graphics2D.setBackground(Color.decode(bgRgb));
        graphics2D.clearRect(0, 0, width, height);
        FontMetrics metrics = graphics2D.getFontMetrics(font);
        graphics2D.setFont(font);
        int x = (width - metrics.stringWidth(text)) / 2;
        int y = ((height - metrics.getHeight()) / 2) + metrics.getAscent();
        graphics2D.drawString(text, x, y - 5);
        graphics2D.dispose();
        bufferedImage.flush();
        ImageIO.write(bufferedImage, "png", outputStream);
    }

}
